package com.wzy.alllearning.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.springframework.stereotype.Service;

import com.wzy.alllearning.exception.BusinessException;
import com.wzy.alllearning.exception.ErrorCodeEnum;
import com.wzy.alllearning.service.FilesService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("localFileServiceImpl")
public class FilesServiceImpl implements FilesService
{
	private static final String BUCKET = "uploads";

	@Override
	public void upload(InputStream inputStream, String fileNmae)
	{
		// 拼接文件存储路径
		String storagePath = BUCKET + "/" + fileNmae;
		// JDK 的try with语法不能关闭外部的资源
		try (InputStream innerInputStream = inputStream;
			 FileOutputStream fileOutputStream = new FileOutputStream(new File(storagePath)))
		{
			final byte[] buffer = new byte[1024];
			int length;
			while ((length = innerInputStream.read(buffer)) > 0)
			{
				fileOutputStream.write(buffer, 0, length);
			}
			// 冲刷这个流
			fileOutputStream.flush();

		}
		catch (Exception ex)
		{
			log.error("文件上传失败 {} {}", ex.toString(), ex.fillInStackTrace());
			throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, ex);
		}
	}

	@Override
	public void upload(File file)
	{
		try
		{
			upload(new FileInputStream(file), file.getName());
		}
		catch (FileNotFoundException ex)
		{
			log.error(ex.toString(), ex.fillInStackTrace());
			throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, ex);
		}
	}
}
